import React, { useEffect, useState } from "react";
import { Button, Form, Input, Table, Popconfirm, Modal } from "antd";
import './user.css'
import { getUser, addUser, editUser, deleteUser } from "../../api";

const User = () => {
    const [ listData, setListData ] =  useState({ name: '' })
    const [ tableData, setTableData] = useState([])
    const [ modalType, setModalType ] = useState([])  // 0 新增 1 编辑表单
    const [ isModalOpen, setIsModalOpen ] = useState(false)
    const [ form ] = Form.useForm()  // 创建form实例

    // 新增/编辑
    const handleClick = (type, rowData) => {
        setIsModalOpen(!isModalOpen)
        if (type === 'add') {
            setModalType(0)
        } else {
            setModalType(1)
            const cloneData = JSON.parse(JSON.stringify(rowData))
            form.setFieldsValue(cloneData)
        }
    }
    // 提交
    const handleFinish = (e) => {
        console.log(e, 'e');
        setListData({
            name: e.keyword
        })
    }
    useEffect(() => {
        getTableData()
    }, [listData])
    // 删除
    const handleDelete = ({ id }) => {
        // console.log(rowData, 'delete');
        deleteUser({ id }).then(() => {
            getTableData()
        })
    }
    const getTableData = () => {
        getUser(listData).then(({ data }) => {
            // console.log(data.list, 'data');
            setTableData(data.list)
        })
    }
    // 弹窗确定
    const handleOk = () => {
        // 表单校验
        form.validateFields().then((val) => {
            if (modalType) {
                // 编辑
                // console.log(val, 'val');
                editUser(val).then(() => {
                    handleCancel()
                    getTableData()
                })
            } else {
                // 新增
                addUser(val).then(() => {
                    handleCancel()
                    getTableData()
                })
            }
        }).catch((err) => {
            console.log(err);
        })
    }
    // 弹窗取消
    const handleCancel = () => {
        setIsModalOpen(false)
        form.resetFields()
    }
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
        },
        {
            title: '用户名',
            dataIndex: 'name',
        },
        {
            title: '账号',
            dataIndex: 'account',
        },
        {
            title: '密码',
            dataIndex: 'password',
        },
        {
            title: '操作',
            render: (rowData) => {
                return (
                    <div className="flex-box">
                        <Button style={{ marginRight: '5px' }} onClick={() => handleClick('edit', rowData)}>编辑</Button>
                        <Popconfirm
                            title="提示"
                            description="此操作将删除该用户，是否继续？"
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => handleDelete(rowData)}
                        >
                            <Button type="primary" danger>删除</Button>
                        </Popconfirm>
                    </div>
                )
            },
        },
    ]
    useEffect(() => {
        // 调用后后端接口获取用户列表数据
        getTableData()
    })

    return (
        <div className="user">
            <div className="flex-box space-between">
                <Button type="primary" onClick={() => handleClick('add')}>+新增</Button>
                <Form
                    layout="inline"
                    onFinish={handleFinish}
                >
                    <Form.Item name="keyword">
                        <Input placeholder='请输入用户名' />
                    </Form.Item>
                    <Form.Item>
                        <Button htmlType="submit" type="primary">搜索</Button>
                    </Form.Item>
                </Form>
            </div>
            <Table style={{marginTop: '10px'}} columns={columns} dataSource={tableData} rowKey={'id'} />
            <Modal
                open={isModalOpen}
                title={ modalType ? '编辑用户' : '新增用户' }
                onOk={handleOk}
                onCancel={handleCancel}
                okText="确定"
                cancelText="取消"
            >
                <Form
                    form={form}
                    labelCol={{
                        span: 6,
                    }}
                    wrapperCol={{
                        span: 18,
                    }}
                    labelAlign="left"
                >
                    {
                        modalType === 1 &&
                        <Form.Item
                            name="id"
                            hidden
                        >
                            <Input />
                        </Form.Item>
                    }
                    <Form.Item
                        label="用户名"
                        name="name"
                        rules={[
                            {
                                required: true,
                                message: '请输入用户名',
                            },
                        ]}
                    >
                        <Input placeholder='请输入用户名'/>
                    </Form.Item>
                    <Form.Item
                        label="账号"
                        name="account"
                        rules={[
                            {
                                required: true,
                                message: '请输入账号',
                            },
                            {
                                pattern: /^[a-zA-Z0-9_-]{4,16}$/,
                                message: '账号由4-16位数字、字母、下划线、减号组成',
                            },
                        ]}
                    >
                        <Input placeholder='请输入账号'/>
                    </Form.Item>
                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[
                            {
                                required: true,
                                message: '请输入密码',
                            },
                            {
                                pattern: /^[a-zA-Z0-9_-]{6,16}$/,
                                message: '密码由6-16位数字、字母、下划线、减号组成',
                            },
                        ]}
                    >
                        <Input placeholder='请输入密码'/>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default User;